import { remove, save, clear } from '../../assets/js/array-store'
import { SEARCH_KEY } from '../../assets/js/constant'
import { useStore } from 'vuex'
import { computed } from 'vue'

export default function useSearchHistory () {
  const store = useStore()
  const maxLen = 100
  const searchHistory = computed(() => store.state.searchHistory)
  const saveSearch = (query) => {
    const searches = save(query, SEARCH_KEY, (item) => {
      return item === query
    }, maxLen)
    store.commit('setSearchHistory', searches)
  }
  const deleteSearch = (query) => {
    const searches = remove(SEARCH_KEY, (item) => {
      return item === query
    })
    store.commit('setSearchHistory', searches)
  }

  const clearSearch = () => {
    const searches = clear(SEARCH_KEY)
    store.commit('setSearchHistory', searches)
  }

  return {
    searchHistory, saveSearch, deleteSearch, clearSearch
  }
}
